package com.yksj.healthtalk.ui.doctor;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.handmark.pulltorefresh.library.PullToRefreshScrollView;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.squareup.timessquare.CalendarFragment;
import com.squareup.timessquare.MonthCellDescriptor;
import com.squareup.timessquare.MonthView.Listener;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.CommonExplainActivity;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.CoreService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.doctor.DoctorCommonServiceActivity.BUTTON;
import com.yksj.healthtalk.ui.views.CalendarTimeFrameView;
import com.yksj.healthtalk.ui.views.CalendarTimeFrameView.PayListener;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.JsonParseUtils;
import com.yksj.healthtalk.utils.SystemUtils;
import com.yksj.healthtalk.utils.ToastUtil;
import com.yksj.healthtalk.utils.ViewFinder;

/**
 * 门诊
 * @author jack_tang
 *
 */
public class DoctorInterviewServiceActivity extends BaseFragmentActivity implements OnClickListener,PayListener,Listener{
	
	CalendarFragment mCalendarFragmentView;
	SimpleDateFormat mDateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");
	SimpleDateFormat mDateFormat2 = new SimpleDateFormat("yyyyMMdd");
	//
	Map<Date, JSONArray> mDataMap = new LinkedHashMap<Date, JSONArray>();

	// 闲忙状态
	Map<Date, String> mStateMap = new LinkedHashMap<Date, String>();
	String mData;
	private TextView mDoctorDescribe;//医生说明
	private CalendarTimeFrameView mCalendarTimeFrameView;
	private Button mBuyBtn;
	private boolean isPay;
	private TextView mMoney;
	private CustomerInfoEntity mCustomerInfoEntity;
	private TextView mContentEt;
	private TextView mPatientName;
	private TextView mPatientPhone;
	private TextView mAddress;
	private TextView mReminderTv;//温馨提示的内容
	private TextView mContentTitle;//服务内容的标题
	private Boolean isServiceBuy ;//已经购买不让点击预约人和电话的标记
	private String SELECTDATE;//购买时需要参数
	private ScrollView mScrollView;
	
	Handler handler=new Handler(){
		public void dispatchMessage(android.os.Message msg) {
			mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
		};
	};
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.doctor_interview_service);
		if (arg0 != null) { 
			mData = arg0.getString("mData");
			mCustomerInfoEntity = arg0.getParcelable("mCustomerInfoEntity");
		} else {
			mData = getIntent().getStringExtra("response");
			mCustomerInfoEntity = (CustomerInfoEntity) getIntent().getExtras().get("mCustomerInfoEntity");
		}
		initWidget();
		initData();
	}
	@Override
	protected void onStart() {
		super.onStart();
		Intent intent =new Intent(this,CoreService.class);
		intent.setAction(CoreService.ACTION_FRAME_VIEW_VISIABLE);
		intent.putExtra("className",this.getClass().getName());
		startService(intent);
	}
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString("mData", mData);
	}
	

	private void initData() {
		if (SmartFoxClient.getLoginUserInfo().isDoctor()) {
			mBuyBtn.setText("对话");
		}
		SimpleDateFormat mDateFormat3 = new SimpleDateFormat("HH:mm");
		JSONObject jsonObject = JSON.parseObject(mData);// TickMesg
		//如果描述为空的话就隐藏
		if(TextUtils.isEmpty(jsonObject.getString("SERVICE_ITEM_DESC"))){
			mDoctorDescribe.setText("欢迎您的光临，很高兴为您服务");
		}else{
			mDoctorDescribe.setText(jsonObject.getString("SERVICE_ITEM_DESC"));
		}
		
		if (jsonObject.getIntValue("witchPage") == 1||jsonObject.getIntValue("witchPage") == 2) {
			JSONArray array = jsonObject.getJSONArray("TickMesg");
//			if (array.size() == 0) {//没有设置预约时段不显示服务内容 价格 等
//				findViewById(R.id.lin_bottom).setVisibility(View.GONE);
//			}
			for (int i = 0; i < array.size(); i++) {
				JSONObject jsonObject2 = array.getJSONObject(i);
				String beginTime = jsonObject2.getString("SERVICE_TIME_BEGIN");
				String busy = jsonObject2.getString("ISBUZY");
				try {
					Date date = mDateFormat2.parse(mDateFormat2.format(mDateFormat1.parse(beginTime)));
					// 记录闲忙
					if (mStateMap.containsKey(date) && "0".equals(busy)) {
						mStateMap.put(date, busy);
					}else if(!mStateMap.containsKey(date)){
						mStateMap.put(date, busy);
					}
					//
					String endTime = jsonObject2.getString("SERVICE_TIME_END");
					beginTime = mDateFormat3.format(mDateFormat1.parse(beginTime));
					endTime = mDateFormat3.format(mDateFormat1.parse(endTime));
					JSONObject object  = new JSONObject();
					object.put("time_space", beginTime + "-" + endTime);
					object.put("SERVICE_ITEM_ID",jsonObject2.getString("SERVICE_ITEM_ID"));
					object.put("SERVICE_PRICE",jsonObject2.getString("SERVICE_PRICE"));
					object.put("ISBUY",jsonObject2.getString("ISBUY"));
					object.put("ISTALK",jsonObject2.getString("ISTALK"));
					object.put("SERVICE_PLACE", jsonObject2.getString("SERVICE_PLACE"));
					object.put("ORDER_ID", jsonObject2.getString("ORDER_ID"));
					object.put("PATIENT_PHONE", jsonObject2.getString("PATIENT_PHONE"));
					object.put("PATIENT_NAME", jsonObject2.getString("PATIENT_NAME"));
					object.put("ADVICE_CONTENT", jsonObject2.getString("ADVICE_CONTENT"));
					object.put("SERVICE_CONTENT", jsonObject2.getString("SERVICE_CONTENT"));
					if (mDataMap.containsKey(date)) {
						mDataMap.get(date).add(object);
					} else {
						JSONArray array2 = new JSONArray();
						array2.add(object);
						mDataMap.put(date, array2);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			List<Date> busy = new ArrayList<Date>();
			List<Date> idley = new ArrayList<Date>();
			for (Map.Entry<Date, String> entry : mStateMap.entrySet()) {
				if (entry.getValue().equals("1")) {
					busy.add(entry.getKey());
				} else {
					idley.add(entry.getKey());
				}
			}
			mCalendarFragmentView.initCalender(null, busy, idley, this);
			// mCalendarFragmentView.
//			mCalendarFragmentView.onUpdateState(busy, idley);
		}else if(jsonObject.getIntValue("witchPage") == 3){//跳转到未支付界面
			Intent intent = new Intent(getApplicationContext(),DoctorInterviewNotPayActivity.class);
			intent.putExtra("response", mData);
			intent.putExtra("mCustomerInfoEntity", mCustomerInfoEntity);
			startActivity(intent);
			finish();
		}
	}

	private void initWidget() {
		initTitle();
		((PullToRefreshScrollView) findViewById(R.id.pull_refresh_scrollview)).setLayoutInvisible();
		mDoctorDescribe = (TextView)findViewById(R.id.describe);
		mContentTitle = (TextView)findViewById(R.id.content_title);
		mCalendarTimeFrameView = (CalendarTimeFrameView) findViewById(R.id.rp);
		mBuyBtn = (Button) findViewById(R.id.buy_btn);
		mMoney = (TextView) findViewById(R.id.money);
		mContentEt = (TextView)findViewById(R.id.content);
		mPatientName = (TextView)findViewById(R.id.patient_name);
		mPatientPhone = (TextView)findViewById(R.id.patient_phone);
		mAddress = (TextView)findViewById(R.id.address);
		mReminderTv= (TextView)findViewById(R.id.reminder);
		
		titleTextV.setText("门诊预约"); 
		mBuyBtn.setVisibility(View.GONE);
		
		titleLeftBtn.setOnClickListener(this);
		mBuyBtn.setOnClickListener(this);
		mCalendarFragmentView = (CalendarFragment) getSupportFragmentManager().findFragmentByTag("calendar");
		
		titleLeftBtn.setOnClickListener(this);
		
		PullToRefreshScrollView ScrollView = (PullToRefreshScrollView) findViewById(R.id.pull_refresh_scrollview);
		mScrollView=ScrollView.getRefreshableView();
	}

	@Override
	public void onClick(View v) {
		// 显示服务金额和地点
		if (v.getTag() != null && v.getTag() instanceof JSONObject) {
			JSONObject object = (JSONObject) v.getTag();
			mMoney.setText(object.getString("SERVICE_PRICE") + "元");
			mAddress.setText(object.getString("SERVICE_PLACE"));
			ViewFinder finder=new ViewFinder(this);
			finder.setText(R.id.service_content, object.getString("SERVICE_CONTENT"));
			mAddress.setVisibility(View.VISIBLE);
			mPatientName.setText(object.getString("PATIENT_NAME"));
			mPatientPhone.setText(object.getString("PATIENT_PHONE"));
			mContentEt.setText(object.getString("ADVICE_CONTENT"));
			findViewById(R.id.lin_bottom).setVisibility(View.VISIBLE);
			handler.sendEmptyMessage(1000);
		}else{
			findViewById(R.id.lin_bottom).setVisibility(View.GONE);
		}
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.buy_btn://购买
			findViewById(R.id.lin_bottom).setVisibility(View.VISIBLE);
			if (isPay ||  SmartFoxClient.getLoginUserInfo().isDoctor()) {
				FriendHttpUtil.onItemClick(this, mCustomerInfoEntity);
			}else {
				if (mCalendarTimeFrameView.getItemId() == null) {
					SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(), "请选择医生的服务时间后在进行购买");
					return;
				}
				//判断是否填写了内容
				if (TextUtils.isEmpty(mPatientPhone.getText().toString().trim())) {
					ToastUtil.showShort(getApplicationContext(), "电话号码不能为空!");
				}else if(TextUtils.isEmpty(mPatientName.getText().toString().trim())){
					ToastUtil.showShort(getApplicationContext(), "患者姓名不能为空!");
				}else if(TextUtils.isEmpty(mContentEt.getText().toString().trim())){
					ToastUtil.showShort(getApplicationContext(), "咨询内容不能为空!");
				}else {
					HttpRestClient.doHttpWalletBalanceServlet(SELECTDATE,HttpRestClient.doHttpPayService(null,SmartFoxClient.getLoginUserId(), mCustomerInfoEntity.getId(), "3", mCalendarTimeFrameView.getItemId(),mContentEt.getText().toString(),mPatientName.getText().toString().trim(),mPatientPhone.getText().toString().trim(), mCalendarTimeFrameView.setObject().getString("SERVICE_PLACE"),new AsyncHander(v.getId())), new AsyncHander(BUTTON.pay.getId()));
				}
			}
			break;
		}
	}
	
	// 患者输入咨询内容
	public void OnClickInputContent(View v) {
		if (isServiceBuy == null || isServiceBuy == false) {
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), CommonExplainActivity.class);
			intent.putExtra("title", "告诉医生");
			intent.putExtra("mContentCount", 200); // 字数限制 默认是200
			 intent.putExtra("content", mContentEt.getText().toString()); // 内容
			startActivityForResult(intent, 0);
		}
	}

	// 服务内容
	public void onClickServcieContent(View v) {
		if (mCalendarTimeFrameView.getItemId() == null) {
			SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(), "请选择医生的服务时间!");
			return;
		}else {
			Intent intent = new Intent(getApplicationContext(),DoctorServiceActivity.class);
			if (mContentTitle.getText().toString().equals("服务内容")) {
				intent.putExtra("userId", mCustomerInfoEntity.getId());
				intent.putExtra("service_type", "3");
				intent.putExtra("service_item_id", mCalendarTimeFrameView.getItemId());
			}else {
				String order_id = mCalendarTimeFrameView.setObject().getString("ORDER_ID");
				if (!TextUtils.isEmpty(order_id)) {
					intent.putExtra("ORIDERID",order_id);
				}else {
					return;
				}
				intent.putExtra("isbuy", true);
			}
			startActivity(intent);
		}
	}
	
	//预约人名称
	public void OnClickPatientName(View v){
		if (isServiceBuy == null || isServiceBuy == false) {
			Intent intent = new Intent();
			intent.setClass(this, CommonExplainActivity.class);
			intent.putExtra("title", "患者名称");
			intent.putExtra("mContentCount", 30); // 字数限制 默认是200
			intent.putExtra("content", mPatientName.getText().toString()); // 内容
			startActivityForResult(intent, 1);
		}
	}
	
	//电话
	public void OnClickPatientPhone(View v){
		if (isServiceBuy == null || isServiceBuy == false) {
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), CommonExplainActivity.class);
			intent.putExtra("title", "手机");
			intent.putExtra("mContentCount", 11); // 字数限制 默认是200
			 intent.putExtra("content", mPatientPhone.getText().toString()); // 内容
			startActivityForResult(intent, 2);
		}
	}
	

	@Override
	public void isCanTalkOrBuy(Boolean isBuy, Boolean isTalk,JSONObject object) {
		//判断服务的标题
		if (isBuy) {
			mContentTitle.setText("所享受服务");
		}
//		mBuyBtn.setBackgroundResource(R.drawable.login_out_btn_selector);
//		mBuyBtn.setTextColor(getResources().getColorStateList(R.color.text_blue));
		//已经购买不让点击预约人和电话的标记
		isServiceBuy  = isBuy;
		
		if ( SmartFoxClient.getLoginUserInfo().isDoctor()) {
			mBuyBtn.setText("看医生");
			mBuyBtn.setBackgroundResource(R.drawable.login_button);
			mBuyBtn.setTextColor(getResources().getColorStateList(R.color.text_green));
			isPay = true;
		}else if (isBuy && !isTalk) {
			mBuyBtn.setVisibility(View.GONE);
			mReminderTv.setText("您已购买此预约服务时段，目前还未到达开始服务时间，请耐心等待。");
			isPay = true;
		}else if(isBuy && isTalk){
			mBuyBtn.setVisibility(View.VISIBLE);
			mBuyBtn.setText("看医生");
			mBuyBtn.setBackgroundResource(R.drawable.login_button);
			mBuyBtn.setTextColor(getResources().getColorStateList(R.color.text_green));
			isPay = true;
		}else if(SmartFoxClient.getLoginUserInfo().isDoctor()){
			mBuyBtn.setVisibility(View.VISIBLE);
			mBuyBtn.setText("看医生");
			mBuyBtn.setBackgroundResource(R.drawable.login_button);
			mBuyBtn.setTextColor(getResources().getColorStateList(R.color.text_green));
			isPay =true;
		}else if((mMoney.getText().toString().trim().subSequence(0, mMoney.getText().toString().trim().length()-1)).equals("0")){
			mBuyBtn.setVisibility(View.VISIBLE);
			mBuyBtn.setText("看医生");
			mBuyBtn.setBackgroundResource(R.drawable.login_button);
			mBuyBtn.setTextColor(getResources().getColorStateList(R.color.text_green));
			//0元
		}else if (object != null && object.containsKey("SERVICE_PRICE") && object.getString("SERVICE_PRICE").equals("0")) {
			mBuyBtn.setText("看医生");
			mBuyBtn.setBackgroundResource(R.drawable.login_button);
			mBuyBtn.setTextColor(getResources().getColorStateList(R.color.text_green));
			isPay = false;
		}else {
			mBuyBtn.setVisibility(View.VISIBLE);
			isPay = false;
			mBuyBtn.setText("购买");
		}		
	}
	
	//网络请求
		public class AsyncHander extends AsyncHttpResponseHandler{
			
			public int buttonId;
			

			public AsyncHander(int buttonId) {
				super(DoctorInterviewServiceActivity.this);
				this.buttonId =  buttonId;
			}


			@Override
			public void onSuccess(int statusCode, String content) {
				try {
					Object object = JSON.parse(content);
					CoreService.actionLogin(DoctorInterviewServiceActivity.this);
					if (object instanceof JSONObject) {
						JSONObject object2 = (JSONObject) object;
						String str = JsonParseUtils.filterErrorMessage(content);
						if ( str != null) {//错误信息
							SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(), str);
						}else if(object2.containsKey("LING") && buttonId == BUTTON.pay.getId()){//价格为0 跳转到 聊天界面
							FriendHttpUtil.onItemClick(DoctorInterviewServiceActivity.this, mCustomerInfoEntity);
						}else  if(object2.containsKey("Balance")&& buttonId == BUTTON.pay.getId()) {
							Intent intent = new Intent(getApplicationContext(),SelectPaymentOptionActivity.class);
							intent.putExtra("url", HttpRestClient.doHttpPayService(SELECTDATE,SmartFoxClient.getLoginUserId(), mCustomerInfoEntity.getId(), "3", mCalendarTimeFrameView.getItemId(),mContentEt.getText().toString(),mPatientName.getText().toString().trim(),mPatientPhone.getText().toString().trim(), mCalendarTimeFrameView.setObject().getString("SERVICE_PLACE"),new AsyncHander(0)));
							intent.putExtra("money",object2.getString("Balance"));
							intent.putExtra("BindPhone", object2.getString("BindPhone"));
							intent.putExtra("isSetPsw", object2.getString("isSetPsw"));
							intent.putExtra("mCustomerInfoEntity", mCustomerInfoEntity);
							startActivity(intent);
							finish();
						}
					}
				} catch (Exception e) {
				}
				super.onSuccess(statusCode, content);
			}
		}
		
	
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent intent) {
		if(arg1!=RESULT_OK || intent==null)return;
		switch (arg0) {
		case 0:
			if (intent.hasExtra("content")) {
				mContentEt.setText(intent.getExtras().getString("content"));
			}
			break;
		case 1:
			if (intent.hasExtra("content")) {
				mPatientName.setText(intent.getExtras().getString("content"));
			}
			break;
		case 2:
			if (intent.hasExtra("content")) {
				mPatientPhone.setText(intent.getExtras().getString("content"));
			}
			break;
		}
		super.onActivityResult(arg0, arg1, intent);
	}

	@Override
	public void onChangeMonth(int i) {
		
	}

	@Override
	public void handleClick(MonthCellDescriptor cell) {
		//点击日历初始数据
		mReminderTv.setText("购买服务后,请您在60分钟内支付,否则订单将会失效!");
		mContentTitle.setText("服务内容");
		mMoney.setText("");
		mAddress.setText("");
		mAddress.setVisibility(View.GONE);
		mPatientName.setText("");
		mPatientPhone.setText("");
		mContentEt.setText("");
		findViewById(R.id.lin_bottom).setVisibility(View.GONE);
		Date date = cell.getDate();
		SELECTDATE = mDateFormat2.format(date);
		if (!mDataMap.containsKey(date)) {
			mCalendarTimeFrameView.removeAllViews();
			mBuyBtn.setVisibility(View.GONE);
			findViewById(R.id.tishi_time).setVisibility(View.GONE);
		}else {
			mBuyBtn.setVisibility(View.VISIBLE);
			
			findViewById(R.id.tishi_time).setVisibility(View.VISIBLE);
			try {
				JSONArray array = mDataMap.get(date);
				LinkedHashMap<String, JSONObject> map = new LinkedHashMap<String, JSONObject>();
				for (int i = 0; i < array.size(); i++) {
					String str = array.getJSONObject(i).getString("time_space");
					map.put(str, array.getJSONObject(i));
				}
				mCalendarTimeFrameView.initView(getApplicationContext(),map);
			} catch (Exception e) {
			}
		}
		handler.sendEmptyMessage(1000);
	}
}
